package cn.itcast.factory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import cn.itcast.service.IAccountService;
import cn.itcast.service.impl.AccountServiceImpl;
import cn.itcast.utils.Logger;
import cn.itcast.utils.TransactionManager;

/**
 * 模拟一个工厂类
 * @author zhy
 *
 */
public class BeanFactory {

	public static IAccountService getAccountBean(){
		final IAccountService accountService = new AccountServiceImpl();
		IAccountService proxyAccountService = (IAccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), 
							accountService.getClass().getInterfaces(), 
							new InvocationHandler() {
								/**
								 * 添加事务的支持
								 */
								@Override
								public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
									
									if("transfer".equals(method.getName())){
										try{
											//开启事务 
											TransactionManager.startTransaction();
											//执行方法
											method.invoke(accountService, args);
											//提交事务
											TransactionManager.commit();
											Logger.printLog();
										}catch(Exception e){
											//回滚事务
											TransactionManager.rollback();
											e.printStackTrace();
										}finally{
											//释放资源
											TransactionManager.release();
										}
									}
									return null;
								}
							});
		return proxyAccountService;
	}
}
